package itsm.isperp.module.service.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.commons.repository.BaseRepository;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.utils.Pair;
import itsm.isperp.module.entity.app.AppConfig;
import itsm.isperp.module.repository.app.AppConfigMapper;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AppConfigService extends BaseService<AppConfig> {

	@Autowired
	protected AppConfigMapper appConfigMapper;

	@Override
	public BaseRepository<AppConfig> getRepository() {
		return this.appConfigMapper;
	}

	public int saveOrUpdate(List<Pair<String, String>> keyAndValue) {

		for (Pair<String, String> kv : keyAndValue) {
			AppConfig appConfig = new AppConfig();
			appConfig.setItemKey(kv.getLeftObject());
			appConfig.setItemValue(kv.getRightObject());
			AppConfig temp = this.findOneByItemName(kv.getLeftObject());
			if (temp != null) {
				appConfig.setId(temp.getId());
			}

			super.saveOrUpdate(appConfig);
		}
		ContextHolder.rebuildConfigs();
		return 1;
	}

	@Override
	public int saveOrUpdate(AppConfig entity) {
		super.saveOrUpdate(entity);
		ContextHolder.rebuildConfigs();
		return 1;
	}

	public int saveOrUpdateButSpecific(AppConfig entity,
			Set<String> unIncludeColumns) {
		super.saveOrUpdateButSpecific(entity, unIncludeColumns);
		ContextHolder.rebuildConfigs();
		return 1;
	}

	public int saveOrUpdate(AppConfig entity, Set<String> includeColumns) {
		super.saveOrUpdateSpecific(entity, includeColumns);
		ContextHolder.rebuildConfigs();
		return 1;
	}

	/**
	 * 根据key或者配置项
	 * 
	 * @param itemKey
	 *            配置项key
	 * @return 配置项实体
	 */
	public AppConfig findOneByItemName(String itemKey) {
		return appConfigMapper.findOneByItemName(itemKey);
	}

}
